using Godot;

namespace Presents.Scripts {
    public class Player : KinematicBody2D {

        [Export] private float _moveSpeed;

        [Export] private float _maxJumpHeight;
        [Export] private float _minJumpHeight;

        private const float Gravity = 360;
        private const float MaxGravity = 175;
        private bool _hasDoubleJumped;
        private Vector2 _moveDir = Vector2.Zero;

        public override void _Ready(){
        
        }

        public override void _Process(float delta){
            MoveAndSlide(GetMotion(delta), Vector2.Up, true);
            GetFacingDir();
            
            
            
            //DEBUG
            if(Input.IsActionJustPressed("ui_cancel"))
            {
                GetTree().Quit();
            }
        }

        private void GetFacingDir(){
            if (Input.IsActionJustPressed("ui_left"))
            {
                Scale = new Vector2(-1, Scale.y);
            } 
            if (Input.IsActionJustPressed("ui_right"))
            {
                Scale = new Vector2(1, Scale.y);
            }
        }
        private Vector2 GetMotion(float delta){
            
            _moveDir.x = ((Input.IsActionPressed("ui_left") ? -1 : 0) + (Input.IsActionPressed("ui_right") ? 1 : 0)) *
                         _moveSpeed;
            _moveDir.y += Gravity * delta;
            if (_moveDir.y >= MaxGravity && !Input.IsActionJustPressed("ui_select"))
                _moveDir.y = MaxGravity;
            if (Input.IsActionJustPressed("ui_select") && IsOnFloor())
            {
                _moveDir.y = -_maxJumpHeight;
            }

            if (Input.IsActionJustPressed("ui_select") && !IsOnFloor() && !_hasDoubleJumped)
            {
                _moveDir.y = -_maxJumpHeight;
                _hasDoubleJumped = true;
            }

            if (Input.IsActionJustReleased("ui_select") && (_moveDir.y <= -_minJumpHeight))
            {
                _moveDir.y = -_minJumpHeight;
            }

            if (IsOnFloor())
            {
                _hasDoubleJumped = false;
            }

            if (IsOnCeiling())
            {
                _moveDir.y = Gravity * delta;
            }

            return _moveDir;

        }

    }
}
